package humynn.engine
{
	/**
	 * Manages updating and drawing multiple screens.
	 */
	public class ScreenManager
	{
		private var _screens:Array;
		private var _newScreens:Array;
		private var _remScreens:Array;
		private var _arrayLock:Boolean;
		
		public function ScreenManager()
		{
			_screens = new Array();
			_newScreens = new Array();
			_remScreens = new Array();
			_arrayLock = false;
		}
		
		/**
		 * Adds a new screen to the addition queue.
		 * 
		 * @param screen The screen to add.
		 */
		public function addScreen(screen:Screen):void
		{
			_newScreens.push(screen);
		}
		
		/**
		 * Addes a screen to the removal queue.
		 * 
		 * @param screen The screen to remove.
		 */
		public function remScreen(screen:Screen):void
		{
			_remScreens.push(screen);
		}
		
		/**
		 * Clears the list of screens.
		 */
		public function clear():void
		{
			_newScreens = new Array();
			_remScreens = new Array();
			_screens = new Array();
		}
		
		/**
		 * Updates the screens in order, so long as none of the screens
		 * block updating.
		 * 
		 * @param input The user input.
		 */
		public function updateScene(input:Input):void
		{
			if(_newScreens.length > 0 || _remScreens.length > 0)
			{
				cleanUpScreens();
			}
			
			for each(var screen:Screen in _screens)
			{
				screen.update(input);
				
				if(screen.blocksUpdate)
				{
					break;
				}
			}
		}
		
		/**
		 * Draws the screens in order.
		 * 
		 * @param renderer The renderer to draw to.
		 */
		public function drawScene(renderer:Renderer):void
		{
			for(var i:int = _screens.length - 1; i >= 0; i--)
			{
				Screen(_screens[i]).draw(renderer);
			}
		}
		
		/**
		 * Processes the new and removed screen queues.
		 */
		private function cleanUpScreens():void
		{
			while(_newScreens.length > 0)
			{
				_screens.unshift(_newScreens.shift());
			}
			
			while(_remScreens.length > 0)
			{
				var screen:Screen = _remScreens.pop();
				var index:int = _screens.indexOf(screen);
				if(index != -1)
				{
					_screens.splice(index, 1);
				}
			}
		}
	}
}